<template>
  <div class="mrpView">
    <el-form label-width="4.68vw">
      <el-form-item :label="$t('market.order')" label-width="100px">
        <el-input v-model.trim="Sonum" size="mini" class="oneInput" @keyup.enter.native="MrpInfo()">
          <i
            slot="suffix"
            class="el-input__icon el-icon-search"
            @click="orderVisiblit=true"
          />
        </el-input>
      </el-form-item>
      <el-form-item label-width="50px" style="width: 500px">
        <el-button v-preventReClick type="primary" size="mini" @click="MrpInfo()">{{ $t('market.sun') }}</el-button>
        <el-button type="primary" size="mini" @click="handleExport">{{ $t('btn.toExcel') }}</el-button>
        <el-button v-preventReClick :loading="infoLoad" size="mini" type="primary" @click="isdanjuDialog=true">{{ $t('market.putIn') }}</el-button>
        <el-button :loading="deloading" class="btn1" type="danger" size="mini" @click="deleteMO">{{ $t('shop.delete') }}</el-button>
      </el-form-item>
    </el-form>
    <div>
      <jc-table
        v-if="isRouterAlive"
        id="out-table"
        ref="multipleTable"
        v-loading="loading"
        serial
        table-selection
        get-row-keys="fid"
        :table-data="tableData"
        :table-header="tableHeader"
        table-height="calc(100vh - 200px)"
        @selectionChange="selectHeadel"
      >
        <template v-slot:text2Slot="col">
          <el-link
            type="primary"
            @click="detailPurchase(col.scope.row.fid)"
          >{{ col.scope.row.fbillno }}</el-link>
        </template>
        <!-- 状态 -->
        <template v-slot:billSlot="col">
          <el-tag v-if="col.scope.row.fstatus === '已转'" type="success">{{ $t('market.forwarded') }}</el-tag>
          <el-tag v-if="col.scope.row.fstatus === '未转'" type="danger">{{ $t('market.unconverted') }}</el-tag>
        </template>
        <!--        生产类型-->
        <template v-slot:btnState="col">
          <span v-if="col.scope.row.fstatus === '已转'">{{ col.scope.row.ferpcls }}</span>
          <el-select
            v-else
            v-model="col.scope.row.ferpclsId"
            placeholder="请选择"
            size="mini"
            :disabled="col.scope.row.fstatus === '已转' || col.scope.row.ferpclsId === 69"
          >
            <el-option
              v-for="item in basicData"
              :key="item.fid"
              :label="item.fname"
              :disabled="item.fid === 69"
              :value="item.fid"
            />
          </el-select>
        </template>
        <!--        生产部门-->
        <template v-slot:btnSlot="col">
          <span v-if="col.scope.row.fstatus === '已转'">{{ col.scope.row.fworkshop }}</span>
          <el-autocomplete
            v-else
            v-model="col.scope.row.fworkshop"
            highlight-first-item
            size="mini"
            popper-class="my-autocomplete"
            :fetch-suggestions="querySearch18"
            :disabled="col.scope.row.fstatus==='已转' || col.scope.row.ferpclsId === 69"
            @focus="getBasicUnit('SX_V_WORKSHOP', col.scope.$index)"
            @select="selUnit"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="handelWorkshop(col.scope.$index)"
            />
            <template slot-scope="{ item }">
              <div class="name">{{ item.fname }}</div>
            </template>
          </el-autocomplete>
        </template>
        <!--     仓库   -->
        <template v-slot:tagSlot="col">
          <span v-if="col.scope.row.fstatus === '已转'">{{ col.scope.row.fstock }}</span>
          <el-autocomplete
            v-else
            v-model="col.scope.row.fstock"
            highlight-first-item
            size="mini"
            popper-class="my-autocomplete"
            :fetch-suggestions="querySearch21"
            :disabled="col.scope.row.fstatus==='已转'"
            @focus="handleWarehouse(col.scope.$index)"
            @select="warehouseSelectRow"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="handleWarehouse1(col.scope.$index)"
            />
            <template slot-scope="{ item }">
              <div class="name">{{ item.fname }}</div>
            </template>
          </el-autocomplete>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <!--        生产单号-->
        <template v-slot:btnStates="col">
          <el-link @click="pushView">{{ col.scope.row.fsourcebillno }}</el-link>
        </template>
        <!--     到货完工日期   -->
        <template v-slot:text3Slot="col">
          <span v-if="col.scope.row.fstatus === '已转'">{{ col.scope.row.fplanfinishdate }}</span>
          <el-date-picker
            v-else
            v-model="col.scope.row.fplanfinishdate"
            type="date"
            value-format="yyyy-MM-dd"
            size="mini"
            @change="planfinHeadel(col.scope.row)"
          />
        </template>
      </jc-table>
      <div class="footer">
        <jc-pagination
          :total="total"
          :page.sync="currentPage"
          :limit.sync="size"
          @pagination="handleGetUntreated"
        />
      </div>
    </div>
    <el-dialog
      v-dialogDrag
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      top="5vh"
      center
      append-to-body
    >
      <div style="text-align: center;height: 100px;padding: 20px 0;">
        整单合并:
        <el-checkbox v-model="fmerge" style="line-height: 28px">全部分录行一并下推</el-checkbox><br>
        <span style="color: red">备注：仅支持采购申请类的订单合并</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="InsertMO()">
          {{ $t('btn.confirm') }}
        </el-button>
      </span>
    </el-dialog>
    <!--  销售单价弹窗-->
    <order-num v-if="orderVisiblit" :selece="false" @xsddh="orderData" />
    <!--  下游单号-->
    <unit v-if="unitVisabled" :msg="funit" @unit="selUnit" />
    <!--    仓库-->
    <selectCK v-if="openWarehouse" @client="warehouseSelectRow" />
  </div>
</template>
<script>
import {
  MrpInfo,
  InsertMO
} from '@/api/mrpView'
import orderNum from '@/views/production/planManagement/mrpView/componenta/orderNum'
import {
  export_json_to_excel,
  formatJson
} from '@/utils/Export2Excel'
import { queryViewItem } from '@/api/marketManage/marketOrder'
import {
  deletePlnPlanorder,
  queryPlnPlanorderList,
  updatePlnPlanorder,
  updatePlnPlanorderList
} from '@/api/production/productionList'
import searData from '@/components/Search/mixin'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
export default {
  name: 'MrpView',
  components: {
    unit: () => import('@/views/basic/createMateriel2/components/unit'),
    selectCK: () => import('@/views/production/collect/components/seleceCK'),
    orderNum
  },
  mixins: [searData, autocomplete],
  data() {
    return {
      orderVisiblit: false, // 销售订单号弹窗
      unitVisabled: false, // 销售订单号弹窗
      isdanjuDialog: false,
      fmerge: false,
      funit: 'SX_V_WORKSHOP',
      ddlx: '', // 订单类型
      itemCode: '', // 物料编号
      storkVisiblit: false, // 生产部门
      Sonum: '', // 销售订单号
      indexSelf: '', // 下标
      seleteFid: [],
      tableData: [],
      tableHeader: [
        // { label: this.$t('market.coding'), type: 'text2', prop: 'fbillno', width: '110' },
        { label: this.$t('shop.state'), type: 'bill', prop: 'fstatus', width: '80', filterHeaders: true },
        { label: this.$t('market.paezText1'), prop: 'fpaezText', filterHeaders: true },
        { label: this.$t('market.transDate'), prop: 'fcreateDate', width: '100' },
        { label: this.$t('market.cpBillno'), prop: 'productnumber', filterHeaders: true, minWidth: '80' },
        { label: this.$t('market.productmolde'), prop: 'productmolde', filterHeaders: true, minWidth: '80' },
        { label: this.$t('market.orderqty'), prop: 'forderqty', width: '80' },
        { label: this.$t('market.funit'), prop: 'funit', width: '80' },
        { label: this.$t('market.salOrder'), prop: 'freleasetype', width: '100', filterHeaders: true, sortable: true },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'fnumber', minWidth: '120px', sortable: true },
        { label: this.$t('market.fmodel'), prop: 'fmodel', minWidth: '120px', filterHeaders: true },
        { label: this.$t('shop.fname2'), prop: 'fname', minWidth: '120px', filterHeaders: true },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion', minWidth: '120px', filterHeaders: true },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', align: 'left', minWidth: '300px', headerAlign: 'center' },
        { label: this.$t('market.sourcebillno'), type: 'states', prop: 'fsourcebillno', width: '110', filterHeaders: true },
        { label: this.$t('market.proType'), type: 'state', prop: 'ferpcls', filterHeaders: true },
        { label: this.$t('market.prodept'), type: 'btn', prop: 'fworkshop', width: '100', filterHeaders: true },
        { label: this.$t('market.stock2'), type: 'tag', prop: 'fstock', width: '130', filterHeaders: true },
        { label: this.$t('market.aogfinishdate'), type: 'text3', prop: 'fplanfinishdate', width: '120' }
      ],
      total: 0,
      size: 200,
      currentPage: 1,
      insetData: {
        CreateID: '',
        Sonum: '',
        insert_MoLists: []
      },
      loading: false,
      infoLoad: false, // 按钮loading
      deloading: false, // 删除按钮loading
      // 仓库
      openWarehouse: false, // 仓库弹窗
      isRouterAlive: true,
      val: [],
      basicData: [],
      MRPDATA: [], // 运算数据
      showCode: 0
    }
  },
  created() {
    this.getMaterielType()
    if (this.$route.params.XSDDH?.length > 0) {
      this.orderVisiblit = true
      // this.orderData(this.$route.params)
    }
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.val.length === 0) {
          this.$message.warning('请选择导出数据')
        } else {
          const list = this.val
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '生产拆单')
        }
      })
    },
    reload() {
      this.isRouterAlive = false
      this.$nextTick(function() {
        this.isRouterAlive = true
      })
    },
    // 获取表格数据 前验证
    async MrpInfo() {
      if (this.MRPDATA.length === 0) return
      this.reload()
      this.loading = true
      const DATA = {
        mrp: this.MRPDATA
      }
      await MrpInfo(DATA).then(res => {
        if (res.code === 0) {
          this.loading = false
          // 获取计划列表数据
          this.handleGetUntreated()
        } else {
          this.loading = false
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      })
    },
    // 确认下发
    async InsertMO() {
      this.insetData.mrp = []
      this.val.map(res => {
        if (res.fstatus === '未转') {
          this.insetData.mrp.push(res)
        }
      })
      if (this.insetData.mrp.length === 0) {
        this.$confirm('没有可转订单', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
        return
      }
      const DATA = {
        ...this.insetData,
        fmerge: this.fmerge
      }
      this.$confirm('是否确认投放?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.infoLoad = true
        InsertMO(DATA).then(res => {
          if (res.code === 0) {
            this.isdanjuDialog = false
            this.val = []
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.handleGetUntreated()
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
          this.infoLoad = false
        })
      })
    },
    // 获取计划列表数据
    async handleGetUntreated() {
      const DATA = {
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData,
        mrp: this.mrpval
      }
      const RES = await queryPlnPlanorderList(DATA)
      if (RES.code === 0) {
        // this.$nextTick(() => {
        //   this.$refs.multipleTable.doLayout()
        // })
        this.tableData = RES.data.array
        this.total = RES.data.total
      } else {
        this.$confirm(RES.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 获取物料类型
    async getMaterielType() {
      const { data: RES } = await queryViewItem({
        viewName: 'SX_V_UNIT_ERPCLSID'
      })
      this.basicData = RES.list
    },
    // 接受子组件传值,获取销售订单号
    orderData(ev) {
      this.Sonum = ''
      this.mrpval = []
      if (ev.XSDDH && ev.XSDDH.length > 0) {
        this.MRPDATA = ev.XSDDH
        ev.XSDDH.forEach(res => {
          this.mrpval.push(res.fsaleorderentryid || res.fentryId)
          this.Sonum += res.fsaleorderno + ','
        })
        this.MrpInfo()
      }
      this.orderVisiblit = false
    },
    // 详情
    detailPurchase(id) {
      this.$router.push(`/planDetails/${id}`)
    },
    // 多选时触发的事件
    selectHeadel(val) {
      this.val = val
      this.seleteFid = []
      this.seleteAll = []
      val.forEach(item => {
        this.seleteFid.push(item.fid)
        this.seleteAll.push(item.fbillno)
      })
    },
    // 删除
    deleteMO() {
      this.deloading = true
      const DATA = {
        Numbers: this.seleteAll
      }
      this.$confirm('确定要删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePlnPlanorder(DATA).then(res => {
          if (res.code === 0) {
            this.seleteAll = []
            this.innerHTM = ''
            this.handleGetUntreated()
            res.data.forEach(res => {
              this.innerHTM += '<div>' + res + '</div>'
            })
            this.$notify.warning({
              title: '提示',
              message: this.innerHTM,
              duration: 3000, offset: 50,
              dangerouslyUseHTMLString: true
            })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
          this.deloading = false
        })
      })
    },
    handelWorkshop(index) {
      this.indexSelf = index
      this.unitVisabled = true
    },
    // 生产部门接受子组件传值
    selUnit(ev) {
      if (ev.fid) {
        const item = this.tableData[this.indexSelf]
        item.fworkshop = ev.fname
        item.fworkshopId = ev.fid
        this.editLx(item)
      }
      this.unitVisabled = false
    },
    // 仓库列表
    async handleWarehouse1(index) {
      this.openWarehouse = true
      this.indexSelf = index
    },
    // 双击仓库弹窗
    warehouseSelectRow(ev) {
      if (ev.fstockId) {
        const item = this.tableData[this.indexSelf]
        item.fstockId = String(ev.fstockId)
        item.fstock = ev.fname
        this.editLx(item)
      }
      this.openWarehouse = false
    },
    // 修改生产类型	生产部门	仓库
    editLx(item) {
      const DATA = {
        fid: item.fid,
        ferpclsId: item.ferpclsId,
        fstockId: item.fstockId,
        fworkshopId: item.fworkshopId
      }
      updatePlnPlanorder(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
          this.handleGetUntreated()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      })
    },
    // 生产单号跳转树形生产管理
    pushView() {
      this.$router.push({ path: '/treeProduction', query: {
        fbillNo: this.Sonum.split(',')[0]
      }})
    },
    // 修改到货完工日期
    planfinHeadel(ev) {
      const DATA = {
        SourceIds: this.seleteFid.length === 0 ? [ev.fid] : this.seleteFid,
        fplanfinishdate: ev.fplanfinishdate
      }
      updatePlnPlanorderList(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
          this.handleGetUntreated()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.mrpView {
  padding: 10px;
  background: #fff;
  .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      width: 13.676vw;
      margin-bottom: 5px;
    }
    .el-form-item:nth-child(1) {
      width: 16.676vw;
    }
  }
  .oneInput {
    width: 11.676vw;
    .el-input__inner {
      padding: 0 5px;
    }
  }
  .el-tag {
    height: 20px;
    line-height: 20px;
  }
}
</style>
